import { ref, watch } from 'vue'
import { usePreferredDark } from '@vueuse/core'

const THEME_KEY = 'website-theme'

export function useTheme() {
  // 从本地存储获取主题设置，如果没有则使用系统主题
  const storedTheme = localStorage.getItem(THEME_KEY)
  const systemDark = usePreferredDark()
  const isDark = ref(storedTheme === null ? systemDark.value : storedTheme === 'dark')
  
  // 监听主题变化并保存到本地存储
  watch(isDark, (newValue) => {
    if (newValue) {
      document.documentElement.classList.add('dark')
      localStorage.setItem(THEME_KEY, 'dark')
    } else {
      document.documentElement.classList.remove('dark')
      localStorage.setItem(THEME_KEY, 'light')
    }
  }, { immediate: true })

  // 只在首次加载时同步系统主题
  watch(systemDark, (newValue) => {
    if (localStorage.getItem(THEME_KEY) === null) {
      isDark.value = newValue
    }
  })

  const toggleTheme = () => {
    isDark.value = !isDark.value
  }

  return {
    isDark,
    toggleTheme
  }
}